package com.gvitz.transaction.database;


import java.security.GeneralSecurityException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.Toast;

import com.gvitz.transaction.R;
import com.gvitz.transaction.activities.MainActivity;
import com.gvitz.transaction.models.Card;
import com.gvitz.transaction.utils.Config;
import com.gvitz.transaction.utils.EncriptUtils;

public class webserviceCards {
	
	
	 public ProgressDialog pDialog; 
	 public Context ctx;
	 public Activity act;
   	 private static final String NAMESPACE = "http://gvitz_webservice/";
   	 private static final String URL = Config.IP + "WSCards?wsdl"; 
	 
	 
	public webserviceCards(Context ctx, Activity act) {
		super();
		this.ctx = ctx;
		this.act = act;
		Config.trustEveryone();
	}
	
	 public void insertCardC(String id_usuario,String number, String exp_month, String exp_year, String type,String name){
		    
		    new insertCardAC().execute(id_usuario, number,exp_month, exp_year, type, name);
	   }
	 
	 public void insertCardD(String id_usuario,String number,String name){
		    
		    new insertCardAD().execute(id_usuario, number, name);
	   }
	   
	 public void GetCards(String id_usuario){
		    
		     new getCardsA().execute(id_usuario);
	  }
	 
	 public void DeleteCard(String id_tarjeta){
		    
	     new DeleteCard().execute(id_tarjeta);
  }

     public class insertCardAC extends AsyncTask< String, String, String > {
	    	

	   	 private static final String METHOD_NAME ="getC";
	   	 private static final String SOAP_ACTION =  "http://gvitz_webservice/getC";
	   	 String id_usuario,number, exp_month,  exp_year,  type, cvc,  name,result;
	   		 
	        protected void onPreExecute() {
	   		    
	        	pDialog = new ProgressDialog(act);
	            pDialog.setMessage("Creando Tarjeta Credito");
	            pDialog.setIndeterminate(false);
	            pDialog.setCancelable(false);
	            pDialog.show();
	            
	        }
	 
			@SuppressWarnings("deprecation")
			protected String doInBackground(String... params) {
				
	              id_usuario=params[0];
	              number=params[1];
	              exp_month=params[2];
	              exp_year=params[3];
	              type=params[4];
	              name=params[5];
				
				  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 

				  // Crear variables

				  PropertyInfo propInfo=new PropertyInfo();
				  propInfo.name="id_usuario";
				  propInfo.type=PropertyInfo.STRING_CLASS;
				 
				  PropertyInfo propInfo1=new PropertyInfo();
				  propInfo1.name="encode";
				  propInfo1.type=PropertyInfo.STRING_CLASS;
				  
				  PropertyInfo propInfo2=new PropertyInfo();
				  propInfo2.name="name";
				  propInfo2.type=PropertyInfo.STRING_CLASS;
				 
				  SharedPreferences prefs=  act.getSharedPreferences("preferencias", Context.MODE_PRIVATE);
				  			  
				  String cadena = number + "-" + exp_month  + "-" +  exp_year  + "_1";			  
				  String numberEnc = "";
					try {
						numberEnc = EncriptUtils.encrypt(cadena,prefs.getString("encode_usuario",""));
					} catch (GeneralSecurityException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				  
				  request.addProperty(propInfo,id_usuario);
				  request.addProperty(propInfo1,numberEnc);
				  request.addProperty(propInfo2,name);


				  //realizar pedido
				  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
				  envelope.setOutputSoapObject(request);			  
				  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
				  					
					  try {
					   
						  //realizar peticion
						   androidHttpTransport.call(SOAP_ACTION, envelope);					   
						   SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();					   
						   result = resultsRequestSOAP.toString();
					   
					  } catch (Exception e) {
						  e.printStackTrace();
						  result="SOAP";
						 
					  }
				return result;	
			}
	       
	        protected void onPostExecute(String result) {
	                                 
				pDialog.dismiss();
				
				if(result.equals("err")){
					result="Error al agregar la tarjeta";
					Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
				}
				else{
					
					if(result.equals("SOAP")){
						result="Error de conexion";
						Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
					}
					else{
					gvitzDB dbHelper = new gvitzDB(ctx);
					int lengh = number.length();
			 		dbHelper.AddTarjeta(new Card(Integer.parseInt(result), name, type,number.substring((lengh -4), lengh)));
			 		
					result="Tarjeta agregada correctamente";
					Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
			 		
				 	Intent i=new Intent(act, MainActivity.class);
				 	act.startActivity(i); 
					act.overridePendingTransition (R.anim.open_next, R.anim.close_main);
					act.finish();
					}
					
				}
     
	          }		
	        }
	
     public class insertCardAD extends AsyncTask< String, String, String > {
	    	

	   	 private static final String METHOD_NAME ="getC";
	   	 private static final String SOAP_ACTION =  "http://gvitz_webservice/getC";
	   	 String id_usuario,number, name,result;
	   		 
	        protected void onPreExecute() {
	   		    
	        	pDialog = new ProgressDialog(act);
	            pDialog.setMessage("Creando Tarjeta Debito");
	            pDialog.setIndeterminate(false);
	            pDialog.setCancelable(false);
	            pDialog.show();
	            
	        }
	 
			@SuppressWarnings("deprecation")
			protected String doInBackground(String... params) {
				
	              id_usuario=params[0];
	              number=params[1];
	              name=params[2];
				
				  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 

				  // Crear variables

				  PropertyInfo propInfo=new PropertyInfo();
				  propInfo.name="id_usuario";
				  propInfo.type=PropertyInfo.STRING_CLASS;
				 
				  PropertyInfo propInfo1=new PropertyInfo();
				  propInfo1.name="encode";
				  propInfo1.type=PropertyInfo.STRING_CLASS;
				  
				  PropertyInfo propInfo2=new PropertyInfo();
				  propInfo2.name="name";
				  propInfo2.type=PropertyInfo.STRING_CLASS;
				 
				  SharedPreferences prefs=  act.getSharedPreferences("preferencias", Context.MODE_PRIVATE);
				  			  
				  String cadena = number + "_2";			  
				  String numberEnc = "";
				
				  try {
					numberEnc = EncriptUtils.encrypt(cadena,prefs.getString("encode_usuario",""));
					} catch (GeneralSecurityException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				  
				  request.addProperty(propInfo,id_usuario);
				  request.addProperty(propInfo1,numberEnc);
				  request.addProperty(propInfo2,name);


				  //realizar pedido
				  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
				  envelope.setOutputSoapObject(request);			  
				  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
				  					
					  try {
					   
						  //realizar peticion
						   androidHttpTransport.call(SOAP_ACTION, envelope);					   
						   SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();					   
						   result = resultsRequestSOAP.toString();
					   
					  } catch (Exception e) {
						  e.printStackTrace();
						  result="SOAP";
						 
					  }
				return result;	
			}
	       
	        protected void onPostExecute(String result) {
	                                 
				pDialog.dismiss();
				
				if(result.equals("err")){
					result="Error al agregar la tarjeta";
					Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
				}
				else{
					
					if(result.equals("SOAP")){
						result="Error de conexion";
						Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
					}
					else{
					gvitzDB dbHelper = new gvitzDB(ctx);
					int lengh = number.length();
			 		dbHelper.AddTarjeta(new Card(Integer.parseInt(result), name,"Debito",number.substring((lengh -4), lengh)));
			 		
					result="Tarjeta agregada correctamente";
					Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
			 		
				 	Intent i=new Intent(act, MainActivity.class);
				 	act.startActivity(i); 
					act.overridePendingTransition (R.anim.open_next, R.anim.close_main);
					act.finish();
					}
					
				}
     
	          }		
	        }
     
     public class getCardsA extends AsyncTask< String, String, String > {
    	
	   	 private static final String METHOD_NAME ="sentC";
	   	 private static final String SOAP_ACTION =  "http://gvitz_webservice/sentC";
	   	 String id_usuario, result;
	   		 
	        protected void onPreExecute() {	   		    
	        //nada de momento
	        }
	 
			@SuppressWarnings("deprecation")
			protected String doInBackground(String... params) {
				
	              id_usuario =params[0];

				  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 

				  PropertyInfo propInfo=new PropertyInfo();
				  propInfo.name="id_usuario";
				  propInfo.type=PropertyInfo.INTEGER_CLASS;
				  
				  request.addProperty(propInfo,Integer.parseInt(id_usuario)); 


				  //realizar pedido
				  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
				  envelope.setOutputSoapObject(request);			  
				  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
						
					  try {
					   
						  //realizar peticion
						   androidHttpTransport.call(SOAP_ACTION, envelope);				  
						   SoapObject  resultsRequestSOAP = (SoapObject) envelope.bodyIn;
						   int count = resultsRequestSOAP.getPropertyCount();
						   
						   gvitzDB dbHelper= new gvitzDB(ctx);
						   
						   for (int i=0; i<count; i++){
							   SoapObject result =(SoapObject) resultsRequestSOAP.getProperty(i);
							   Card aux = new Card( Integer.parseInt(result.getProperty(0).toString()), result.getProperty(2).toString(), 
									   result.getProperty(3).toString(),  result.getProperty(1).toString());
									  
							   dbHelper.AddTarjeta(aux);

							   }
						  
						   result = "ok";
					   
					  } catch (Exception e) {
						  result="SOAP";						 
					  }
				return result;	
			}
	       
	        protected void onPostExecute(String result) {                   							    

	          }		
	        }
	
     public class DeleteCard extends AsyncTask< String, String, String > {
    	

	   	 private static final String METHOD_NAME ="deleteC";
	   	 private static final String SOAP_ACTION =  "http://gvitz_webservice/deleteC";
	   	 String id_tarjeta,result;
	   		 
	        protected void onPreExecute() {
	   		    
	        	pDialog = new ProgressDialog(act);
	            pDialog.setMessage("Borrando Tarjeta del sistema");
	            pDialog.setIndeterminate(false);
	            pDialog.setCancelable(false);
	            pDialog.show();
	            
	        }
	 
			@SuppressWarnings("deprecation")
			protected String doInBackground(String... params) {
				
	              id_tarjeta=params[0];

				
				  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 

				  // Crear variables

				  PropertyInfo propInfo=new PropertyInfo();
				  propInfo.name="id_tarjeta";
				  propInfo.type=PropertyInfo.STRING_CLASS;

				  request.addProperty(propInfo,id_tarjeta); 


				  //realizar pedido
				  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
				  envelope.setOutputSoapObject(request);			  
				  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
						
					  try {
					   
						  //realizar peticion
						   androidHttpTransport.call(SOAP_ACTION, envelope);				  
						   SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();					   
						   result = resultsRequestSOAP.toString();
					   
					  } catch (Exception e) {
						  
						  result="SOAP";
						 
					  }
				return result;	
			}
	       
	        protected void onPostExecute(String result) {
	                                 
				pDialog.dismiss();
				
				if(result.equals("SOAP")){
					result="Error de conexion";
					Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();	
				}
				else{
					
					if(result.equals("ok")){
						result="Tarjeta borrada correctamente";
						Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
					}
					else{
						result="Error al borrar la tarjeta";
						Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
						
					}
    
	          }		
	        }   
     }
}
